// pages/treehollow/treehollow.js
import {getMpTreeholeList} from '../../api/treehollow'
Page({
  data: {
    treeholeList: [],
    loading: false,
    hasMore: true,
    pageNo: 1,
    pageSize: 10
  },
  onLoad(options) {
    this.loadTreeholeList()
  },
  onShow() {
    // 检查是否需要刷新
    if (getApp().globalData.shouldRefreshTreeholeList) {
      this.refreshList()
      getApp().globalData.shouldRefreshTreeholeList = false
    }
  },
  // 加载树洞列表
  async loadTreeholeList(isRefresh = false){
    if(this.data.loading) return 
    this.setData({loading: true})
    try {
      const pageNo = isRefresh ? 1 : this.data.pageNo
      const result = await getMpTreeholeList(pageNo,this.data.pageSize)
      console.log("树洞列表数据",result);
      // 处理接口返回的数据结构
      let rawList = result
      if(result && result.list) {
        rawList = result.list
      }
      if(isRefresh) {
        this.setData({
          treeholeList:rawList,
          pageNo:1,
          hasMore:rawList.length>=this.data.pageSize
        })
      } else {
        this.setData({
          treeholeList:[...this.data.treeholeList,...rawList],
          pageNo:pageNo+1,
          hasMore:rawList.length>=this.data.pageSize
        })
      }
    } catch(error) {
      console.error("加载树洞列表失败",error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({loading:false})
    }
  },
  // 刷新列表
  refreshList() {
    this.loadTreeholeList(true)
  },
  // 加载更多
  loadMore() {
    if(!this.data.hasMore || this.data.loading) return 
    this.loadTreeholeList(false)
  },

  // 跳转到详情页
  navigateToDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/treehollow/treehollow-detail/treehollow-detail?id=${id}`
    });
  },

  // 跳转到发布页
  navigateToPublish() {
    wx.navigateTo({
      url: '/pages/treehollow/treehollow-publish/treehollow-publish'
    });
  },

  // 显示更多选项
  showMoreOptions() {
    wx.showActionSheet({
      itemList: ['刷新内容', '举报反馈', '关于树洞'],
      success(res) {
        console.log('选中了第', res.tapIndex, '项');
      }
    });
  },

  onPullDownRefresh() {
    this.refreshList()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },
  onReachBottom() {
    this.loadMore()
  }
});